package com.liguang.rcs.admin.util.excel;

import com.liguang.rcs.admin.exception.BaseException;
import com.liguang.rcs.admin.util.ReflectUtil;
import com.liguang.rcs.admin.util.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;

@Slf4j
public class ExcelExport {
    private final URL templatePath;
    private final int startIndex;
    private Workbook workbook;
    private Sheet sheet;
    private int currentIndex;
    private boolean indexFlag;
    private int dataIndex = 1 ;

    public ExcelExport(URL templatePath, int startIndex) {
        this.templatePath = templatePath;
        this.startIndex = startIndex;
    }

    public void init(boolean indexFlag) {
        //初始化 读取模板文件
        this.workbook = readTemplate();
        this.sheet = this.workbook.getSheetAt(0);
        this.currentIndex = this.startIndex;
        this.indexFlag = indexFlag;
    }

    private Workbook readTemplate() {
        try {
            InputStream fis = this.templatePath.openStream();
            try {
                return new XSSFWorkbook(fis);
            } finally {
                fis.close();
            }
        } catch (Exception ex) {
            log.warn("read template fail, exception:", ex);
            throw new BaseException(ResponseCode.BAD_ARGUMENT_VALUE);
        }
    }

    public void addRow(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        Row row = sheet.createRow(currentIndex++);
        if (indexFlag) {
            row.createCell(0).setCellValue(dataIndex++);
        }
        try {
            for(Field field : fields) {
                ExcelColumnProperty columnProperty = field.getAnnotation(ExcelColumnProperty.class);
                if (columnProperty == null) {
                    continue;
                }
                Cell cell = row.createCell(columnProperty.columnIndex());
                Object value = ReflectUtil.getValue(field, object);
                if (value != null) {
                    cell.setCellValue(String.valueOf(value));
                }
            }
        } catch (Exception ex) {
            log.error("fill to excel fail, Exception:", ex);
            throw new BaseException(ResponseCode.SYS_INNER_ERR);
        }
    }

    public Workbook getWorkbook() {
        return workbook;
    }
}
